/*
 *  Copyright (C) 2020 original author or authors.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 *  in compliance with the License. You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software distributed under the License
 *  is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 *  or implied. See the License for the specific language governing permissions and limitations under
 *  the License.
 */

package vip.justlive.easyproxy.core.httpproxy;

import java.io.IOException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import vip.justlive.easyproxy.core.context.Config;
import vip.justlive.easyproxy.core.context.Metrics;
import vip.justlive.oxygen.core.config.ConfigFactory;
import vip.justlive.oxygen.core.config.Ignore;
import vip.justlive.oxygen.core.net.aio.core.GroupContext;
import vip.justlive.oxygen.core.net.aio.core.Server;
import vip.justlive.oxygen.ioc.annotation.Bean;
import vip.justlive.oxygen.ioc.annotation.PostConstruct;
import vip.justlive.oxygen.ioc.annotation.PreDestroy;

/**
 * http proxy
 *
 * @author wubo
 */
@Bean
@Slf4j
@RequiredArgsConstructor
public class HttpProxyServer {

  private final Config config;
  @Ignore
  private Server server;

  @PostConstruct
  public void init() throws IOException {
    if (config.getHttpProxy().isEnabled()) {
      HttpServerHandler handler = new HttpServerHandler(config);
      GroupContext ctx = new GroupContext(handler).setAioListener(handler);
      ConfigFactory.load(ctx, Config.HTTP_PROXY_AIO_CONFIG);
      server = new Server(ctx);
      server.start(config.getHttpProxy().getHost(), config.getHttpProxy().getPort());
      Metrics.metrics(config.getHttpProxy().getPort());
      log.info("http proxy started {}", server.getServerAddress());
    }
  }

  @PreDestroy
  public void destroy() {
    if (server != null) {
      server.stop();
      log.info("close http proxy {}", server.getServerAddress());
    }
  }
}
